using System;
using System.Net.Sockets;
using Consts;
using Dto;
using Net.Handler;
using UI;
using UI.Msg;
using UnityEngine;

namespace Net
{
    public class NetManager : ManagerBase
    {
        public static NetManager Instance = null;
        private ClientPeer _client = new ClientPeer("127.0.0.1", 6666);

        private void Awake()
        {
            Instance = this;
            Add(0, this);
        }

        public override void Execute(int eventCode, object message)
        {
            switch (eventCode)
            {
                case 0:
                    _client.Send(message as ReqBase);
                    break;
                default:
                    break;
            }
        }

        private void Start()
        {
            OnConnected();
        }


        public void OnConnected()
        {
            _client.Connect();
        }

        private void Update()
        {
            if (_client == null)
                return;

            while (_client.SocketMsgQueue.Count > 0)
            {
                ResBase res = _client.SocketMsgQueue.Dequeue();
                // Debug.Log(res.result);
                processSocketMsg(res);
            }
        }

        private HandlerBase accountHandler = new AccountHandler();
        private HandlerBase matchHandler = new MatchHandler();
        private HandlerBase chatHandler = new ChatHandler();
        private HandlerBase fightHandler = new FightHandler();

        private void processSocketMsg(ResBase msg)
        {
            // 错误提示 
            if (msg.resCode == 500)
            {
                PromptMsg _promptMsg = new PromptMsg(msg.result.ToString(), Color.red);
                MsgCenter.Instance.Dispatch(AreaCode.UI, UIEvent.PROMPT_MSG, _promptMsg);
            }

            switch (msg.code)
            {
                case SocketConst.ACCOUNT:
                    accountHandler.OnReceive(msg);
                    break;
                case SocketConst.MATCH:
                    matchHandler.OnReceive(msg);
                    break;
                case SocketConst.CHAT:
                    chatHandler.OnReceive(msg);
                    break;
                case SocketConst.FIGHT:
                    fightHandler.OnReceive(msg);
                    break;
            }
        }
    }
}